/**
 * anis.darwich
 */

package demo;

import java.awt.Color;
import java.awt.Graphics;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import com.MotionCommand;
import com.SerialComm;

public class RobotCommunication extends SerialComm {
	
	private final static Logger log = Logger.getLogger(RobotCommunication.class);

	private final int delay = 0;
	
	RobotNodeDraw dessin;

	
	public RobotCommunication(String[] args, Graphics graphics) throws Exception {
		super();
		this.openSerialPort("COM7", 9600);
		PropertyConfigurator.configure("log4j.properties");
		this.dessin = new RobotNodeDraw(graphics);
		this.run();
	}
	
	public static void main(String[] args) throws Exception {
		//PropertyConfigurator.configure("log4j.properties");
		//new RobotCommunication(args);
	}
	
	protected Object getLock() {
		return this;
	}
	
	public void process(String p) {
		log.debug(">>> Processing"+ p);
		MotionCommand packet = MotionCommand.parse(p);
		switch (packet.getApiType()) {
			case 5:
				//to do
				log.debug(">>> Received packet with API type " + packet.getApiType() + ", x= " + packet.getX() + ", y= " + packet.getY() + "\n");
				dessin.drawNodePosition(packet.getX(), packet.getY(), Color.red);
				break;
			case 6:
				//to do
				log.debug(">>> Received packet with API type " + packet.getApiType() + ", x= " + packet.getX() + ", y= " + packet.getY() + "\n");
				dessin.drawRobotPosition(packet.getX(), packet.getY(), Color.black);
				break;
			default:
				//to do
				log.debug(">>> Received packet with UNKNOWN API type\n");
				break;
		}
	}
	
	public void run() {
		//MotionCommand rover_command = new MotionCommand( 2, 2); 
		try {	
			//this.sendCommand(rover_command.toSend());
			while (true) {
				synchronized(this.getLock()) {				
					this.getLock().wait(TIMEOUT);
					log.debug(">>> Received " + this.getLastResponse());
					if (this.getLastResponse() != null) {
						this.process(this.getLastResponse());
					}
				}
				Thread.sleep(delay);
			}
		} catch (Throwable th) {
			th.printStackTrace();
		}
	}
}
